package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.SchAddPanelAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.SchAddBean;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.OKHttpUICallback;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.SimpleSpinnerOption;
import cn.acewill.yxd.yunxundian.pubClass.multiSelect;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import okhttp3.Call;

public class schAdd extends BaseActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    static public int fragementid=0;
    private Context mContext;
    private static int thisyear,thismonth,thisday;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sch_add);
        mContext=this;
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("任务添加");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(102);
                finish();

            }
        });
        thisyear = getIntent().getIntExtra("year",0);
        thismonth = getIntent().getIntExtra("month",0)+1;
        thisday = getIntent().getIntExtra("day",0);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        /*
      The {@link ViewPager} that will host the section contents.
     */
        ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }



    public void saveSchToServer(List<SchAddBean> schAddBeen)
    {
        if(NetWorkStateReceiver.whetherConnectNetWork==1) {
            if (schAddBeen != null) {
                OKHttpUICallback.ResultCallback callback=new OKHttpUICallback.ResultCallback() {
                    @Override
                    public void onSuccess(String result) {
                        AsynData ad=new AsynData(null);
                        ad.asynScheduleData(result.toString());
                        if(pubClass.dialog!=null)
                            pubClass.dialog.dismiss();
                        setResult(102);
                        finish();
                    }

                    @Override
                    public void onError(Call call, IOException e) {
                        if(pubClass.dialog!=null) {
                            pubClass.dialog.setTitle("提交失败，请检查网络状况");
                        }
                    }
                };
                Map<String,String> map=new HashMap<>();
                map.put("task","addSchToServerWithType");
                map.put("schjson",JSON.toJSONString(schAddBeen));
                pubClass.dialog = new ProgressDialog(mContext);
                pubClass.dialog.setTitle("正在提交请稍后...");
                pubClass.dialog.show();
                try {
                    OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm,callback,map);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        else
        {
            BaseActivity.showAnimaDialog(this,"请检查网络连接");
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sch_add, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            if(fragementid==0)
            {
                if (PlaceholderFragment.cacheSch!=null&&PlaceholderFragment.cacheSch.size()>0)
                    saveSchToServer(PlaceholderFragment.cacheSch);
                else BaseActivity.showAnimaDialog(this,"请先进行选择");

            }
            else if(fragementid==1)
            {
                if (addFragment2.cacheSch!=null&&addFragment2.cacheSch.size()>0)
                      saveSchToServer(addFragment2.cacheSch);
                else BaseActivity.showAnimaDialog(this,"请先进行选择");
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 任务多餐厅页面.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */

        final Calendar c = Calendar.getInstance();
        private YXDAPP yxdapp=new YXDAPP();
        private DbManager db = x.getDb(yxdapp.getDaoConfig());
        private Button multiSpinner;
        private static final String ARG_SECTION_NUMBER = "section_number";
        private Button addShop;
        private List<SimpleSpinnerOption> lst=new ArrayList<>();
        private List<SimpleSpinnerOption> cacheSTypeList=new ArrayList<SimpleSpinnerOption>();
        private List<SimpleSpinnerOption> shopLst=new ArrayList<SimpleSpinnerOption>();
        private ListView liSchAdd;
        private int position=0;
        private View txV;
        public static List<SchAddBean> cacheSch = new ArrayList<SchAddBean>();
        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_sch_add, container, false);
            //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            multiSpinner = (Button) rootView.findViewById(R.id.mulSpinner);
            multiSpinner.setText("请选择任务类型");
            try {
                Employee employee=db.selector(Employee.class).where("ID","=", String.valueOf( cn.acewill.yxd.yunxundian.ui.MainActivity.id)).findFirst();
                if(employee!=null)
                {
                    List<CommonMapBean> cmbList=db.selector(CommonMapBean.class)
                            .where("cmType","=","role")
                            .and("ServerId","=",employee.getID()+"")
                            .findAll();
                    int isall=1;
                    int isOE=0;
                    if(cmbList!=null)
                    {
                        for(CommonMapBean cc:cmbList)
                        {
                            if(cc.getCmValue().equals("OM"))
                                isall=1;
                            else if(cc.getCmValue().equals("OC"))
                                isall=1;
                            else if(cc.getCmValue().equals("OE")) {
                                isall = 1;
                                isOE = 1;
                            }
                            else
                                isall=1;
                        }
                    }
                    List<sType> typeList=null;
                    if(isOE==0)
                    typeList=db.selector(sType.class).where("isToShop","=","1")
                            .and("areaId","like",employee.getDiqu()==null?"-%":("%-"+employee.getDiqu().toString()+"-%")).findAll();
                    else
                        typeList=db.selector(sType.class).where("isToShop","=","1")
                                .and("departmentId","like",employee.getDepartmentId()==0?"-%":("%-"+employee.getDepartmentId()+"-%")).findAll();

                    if(typeList!=null)
                    {
                        for (sType ss:typeList
                             ) {
                            SimpleSpinnerOption ci=new SimpleSpinnerOption();
                            ci.setValue(String.valueOf(ss.getID()));
                            ci.setName(ss.getTypeName());
                            lst.add(ci);
                        }
                    }

                    List<Shop> shopList=null;
                    if(isall==0)
                        shopList=db.selector(Shop.class).where("ocid","=",String.valueOf(employee.getID())).or("omid","=",String.valueOf(employee.getID())).findAll();

                    if(shopList==null)
                        shopList=db.selector(Shop.class).findAll();
                    if(shopList!=null)
                    {
                        for(Shop thiS:shopList){
                            SimpleSpinnerOption shopS=new SimpleSpinnerOption();
                            shopS.setName(thiS.getShopName());
                            shopS.setValue(String.valueOf(thiS.getID()));
                            shopLst.add(shopS);
                        }
                    }
                }
            }
            catch (DbException e)
            {
                e.printStackTrace();
            }

            multiSpinner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent sel = new Intent(getContext(), multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(lst));
                    sel.putExtra("title", "请选择任务类型");
                    sel.putExtra("xuanze", "dan");
                    sel.putExtra("daima", "sch");
                    //startActivity(sel);
                    startActivityForResult(sel, 1);
                }
            });

            addShop=(Button)rootView.findViewById(R.id.buttonSch);
            addShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent sel=new Intent(getContext(), multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(shopLst));
                    sel.putExtra("title","请选择门店");
                    sel.putExtra("xuanze","duo");
                    sel.putExtra("daima","shop");
                    //startActivity(sel);
                    startActivityForResult(sel,1);
                }
            });

            liSchAdd = (ListView)rootView.findViewById(R.id.schAddPanel);
            freshAddPanel();
            return rootView;
        }
//        int year=c.get(Calendar.YEAR);
//        int month=c.get(Calendar.MONTH)+1;
//        int day=c.get(Calendar.DAY_OF_MONTH);
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minutes=0;
        String sYear="",sMonth="",sDay="",sHH="",sMM="";
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, data);

            if(resultCode==1){
                if(requestCode==1){
                    Gson gson = new Gson();
                    String result = data.getStringExtra("result");
                    String rdaima=data.getStringExtra("daima");
                    Type typeList = new TypeToken<ArrayList<SimpleSpinnerOption>>() {
                    }.getType();
                    String retStr="";
                    ArrayList<SimpleSpinnerOption> results = gson.fromJson(pubClass.convertToArrayJsonNormal(result), typeList);
                    if(rdaima.equals("shop")) {
                        shopLst = results;
                        if (results != null) {
                            for (SimpleSpinnerOption s :
                                    results) {
                                if (s.isChecked() == true)
                                    retStr += s.getName() + ",";
                            }
                            if (!retStr.equals("")) {
                                retStr = retStr.substring(0, retStr.length() - 1);
                                addShop.setText(retStr);
                            } else {
                                addShop.setText("请选择门店");
                            }
                        }
                    }
                    else
                    {
                        lst=results;
                        if (results != null) {
                            for (SimpleSpinnerOption s :
                                    results) {
                                if (s.isChecked() == true)
                                    retStr += s.getName() + ",";
                            }
                            if (!retStr.equals("")) {
                                retStr = retStr.substring(0, retStr.length() - 1);
                                multiSpinner.setText(retStr);
                            } else {
                                multiSpinner.setText("请选择任务类型");
                            }
                        }
                    }
                    freshAddPanel();
                }
            }

        }

        private void freshAddPanel()//任务多餐厅
        {
            fragementid=0;
            if(lst==null)
                return;
            if(shopLst==null)
                return;
            if(lst.size()==0)
                return;
            if(shopLst.size()==0)
                return;
            cacheSch = new ArrayList<SchAddBean>();
            SimpleSpinnerOption schTypeTemp=new SimpleSpinnerOption();
            for(SimpleSpinnerOption ss:lst)
            {
                if(ss.isChecked()){
                    schTypeTemp=ss;
                    break;
                }
            }
            if(schTypeTemp!=null && schTypeTemp.getValue().equals(""))
                return;
            YEARMMDD();
            String str=sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM;
            for (SimpleSpinnerOption s : shopLst) {
                if(s.isChecked()) {
                    SchAddBean sch = new SchAddBean();
                    sch.setShopid(String.valueOf(s.getValue()));
                    sch.setShopname(s.getName());
                    sch.setEmpid(String.valueOf(cn.acewill.yxd.yunxundian.ui.MainActivity.id));
                    sch.setStypeid(String.valueOf(schTypeTemp.getValue()));
                    sch.setSchTypeStr(String.valueOf(schTypeTemp.getName()));
                    sch.setSchStartTime(str);
                    cacheSch.add(sch);
                }
            }
            final SchAddPanelAdapter sapa = new SchAddPanelAdapter(getContext(), cacheSch,new SchAddPanelAdapter.moreTaskCallBack(){
                @Override
                public void Click(SchAddBean bean,View v,int pid) {
                    position=pid;
                    txV=v;
                    //Toast.makeText(getContext(),"test",Toast.LENGTH_SHORT).show();
                    switch (v.getId()){
                        case (R.id.schStartDate):{
                            DatePickerDialog dpd = new DatePickerDialog(getContext(), Datelistener,thisyear , thismonth-1, thisday);
                            dpd.show();//显示DatePickerDialog组件
                            break;
                        }
                        case (R.id.schStartTime):{
                            TimePickerDialog dpd = new TimePickerDialog(getContext(),timeSetListener,9,30,true);
                            dpd.show();//显示DatePickerDialog组件
                            break;
                        }
                    }
                }
                TimePickerDialog.OnTimeSetListener timeSetListener=new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        hour=hourOfDay;
                        minutes=minute;
                        YEARMMDD();
                        cacheSch.get(position).setSchStartTime(sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM);
                        ((TextView)txV).setText(sHH+":"+sMM);
                    }
                };

                DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
                    /**
                     * params：view：该事件关联的组件
                     * params：myyear：当前选择的年
                     * params：monthOfYear：当前选择的月
                     * params：dayOfMonth：当前选择的日
                     */
                    @Override
                    public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {


                        //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
                        thisyear = myyear;
                        thismonth = monthOfYear+1;
                        thisday = dayOfMonth;
                        //更新日期
                        updateDate();
                    }

                    //当DatePickerDialog关闭时，更新日期显示
                    private void updateDate() {
                        YEARMMDD();
                        cacheSch.get(position).setSchStartTime(sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM);
                        ((TextView)txV).setText(sYear+"-"+sMonth+"-"+sDay);
                    }
                };

            });
            liSchAdd.setAdapter(sapa);
            sapa.notifyDataSetChanged();
        }

        public void YEARMMDD()
        {
            sYear=String.valueOf(thisyear);
            sMonth=thismonth+"";
            sDay=thisday+"";
            sHH=hour+"";
            sMM=minutes+"";
            if(String.valueOf(thismonth).length()==1)
            {
                sMonth="0"+thismonth;
            }
            if(String.valueOf(thisday).length()==1)
            {
                sDay="0"+thisday;
            }
            if(String.valueOf(hour).length()==1)
            {
                sHH="0"+hour;
            }
            if(String.valueOf(minutes).length()==1)
            {
                sMM="0"+minutes;
            }
        }
    }

    /**
     * 餐厅多任务页面.
     */
    public static class addFragment2 extends Fragment{
        //private static final String ARG_SECTION_NUMBER = "section_number";
        final Calendar c = Calendar.getInstance();
        private YXDAPP yxdapp=new YXDAPP();
        private DbManager db = x.getDb(yxdapp.getDaoConfig());
        private Button multiSpinner;
        private static final String ARG_SECTION_NUMBER = "section_number";
        private Button addShop;
        private List<SimpleSpinnerOption> lst=new ArrayList<>();
        private List<SimpleSpinnerOption> cacheSTypeList=new ArrayList<>();
        private List<SimpleSpinnerOption> shopLst=new ArrayList<SimpleSpinnerOption>();
        private ListView liSchAdd;
        private int position=0;
        private View txV;
        private Context context;
        public static List<SchAddBean> cacheSch = new ArrayList<SchAddBean>();
        public addFragment2(){
        }

        public static addFragment2 newInstance(int sectionNumber)        {
            addFragment2 fragment = new addFragment2();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            this.context = context;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.sch_add2, container, false);
            //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            multiSpinner = (Button) rootView.findViewById(R.id.mulSpinner);
            multiSpinner.setText("请选择餐厅");
            try {
                Employee employee=db.selector(Employee.class).where("ID","=", String.valueOf( cn.acewill.yxd.yunxundian.ui.MainActivity.id)).findFirst();
                if(employee!=null)
                {


                    List<CommonMapBean> cmbList=db.selector(CommonMapBean.class)
                            .where("cmType","=","role")
                            .and("ServerId","=",employee.getID()+"")
                            .findAll();
                    int isall=1;
                    int isOE=0;
                    if(cmbList!=null)
                    {
                        for(CommonMapBean cc:cmbList)
                        {
                            if(cc.getCmValue().equals("OM"))
                                isall=1;
                            else if(cc.getCmValue().equals("OC"))
                                isall=1;
                            else if(cc.getCmValue().equals("OE")) {
                                isall = 1;
                                isOE=1;
                            }
                            else
                                isall=1;
                        }
                    }
                    List<sType> typeList=null;
                    if(isOE==0) {
                        typeList = db.selector(sType.class).where("isToShop", "=", "1")
                                .and("areaId", "like", employee.getDiqu() == null ? "-%" : ("%-" + employee.getDiqu().toString() + "-%")).findAll();
                    }
                    else
                    {
                        typeList=db.selector(sType.class).where("isToShop","=","1")
                                .and("departmentId","like",employee.getDepartmentId()==0?"-%":("%-"+employee.getDepartmentId()+"-%")).findAll();
                    }
                        if(typeList!=null) {
                            for (sType ss : typeList
                                    ) {
                                SimpleSpinnerOption ci = new SimpleSpinnerOption();
                                ci.setValue(String.valueOf(ss.getID()));
                                ci.setName(ss.getTypeName());
                                lst.add(ci);
                            }
                        }

                    List<Shop> shopList=null;
                    if(isall==0)
                        shopList=db.selector(Shop.class).where("ocid","=",String.valueOf(employee.getID())).or("omid","=",String.valueOf(employee.getID())).findAll();
                    if(shopList==null)
                        shopList=db.selector(Shop.class).findAll();
                    if(shopList!=null)
                    {
                        for(Shop thiS:shopList){
                            SimpleSpinnerOption shopS=new SimpleSpinnerOption();
                            shopS.setName(thiS.getShopName());
                            shopS.setValue(String.valueOf(thiS.getID()));
                            shopLst.add(shopS);
                        }
                    }
                }
            }
            catch (DbException e)
            {
                e.printStackTrace();
            }

            multiSpinner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent sel = new Intent(getContext(), multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(shopLst));
                    sel.putExtra("title", "请选择餐厅");
                    sel.putExtra("xuanze", "dan");
                    sel.putExtra("daima", "shop");
                    //startActivity(sel);
                    startActivityForResult(sel, 1);
                }
            });

            addShop=(Button)rootView.findViewById(R.id.buttonSch);
            addShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent sel=new Intent(getContext(), multiSelect.class);
                    sel.putExtra("lstData", JSON.toJSONString(lst));
                    sel.putExtra("title","请选择任务类型");
                    sel.putExtra("xuanze","duo");
                    sel.putExtra("daima","sch");
                    //startActivity(sel);
                    startActivityForResult(sel,1);
                }
            });

            liSchAdd = (ListView)rootView.findViewById(R.id.schAddPanel);
            freshAddPanel();
            return rootView;
        }

//        int year=c.get(Calendar.YEAR);
//        int month=c.get(Calendar.MONTH)+1;
//        int day=c.get(Calendar.DAY_OF_MONTH);
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minutes=0;
        String sYear="",sMonth="",sDay="",sHH="",sMM="";
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, data);

            if(resultCode==1){
                if(requestCode==1){
                    Gson gson = new Gson();
                    String result = data.getStringExtra("result");
                    String rdaima=data.getStringExtra("daima");
                    Type typeList = new TypeToken<ArrayList<SimpleSpinnerOption>>() {
                    }.getType();
                    String retStr="";
                    ArrayList<SimpleSpinnerOption> results = gson.fromJson(pubClass.convertToArrayJsonNormal(result), typeList);
                    if(rdaima.equals("shop")) {
                        shopLst = results;
                        if (results != null) {
                            for (SimpleSpinnerOption s :
                                    results) {
                                if (s.isChecked())
                                    retStr += s.getName() + ",";
                            }
                            if (!retStr.equals("")) {
                                retStr = retStr.substring(0, retStr.length() - 1);
                                multiSpinner.setText(retStr);
                            } else {
                                multiSpinner.setText("请选择餐厅");
                            }
                        }
                    }
                    else
                    {
                        lst=results;
                        if (results != null) {
                            for (SimpleSpinnerOption s :
                                    results) {
                                if (s.isChecked())
                                    retStr += s.getName() + ",";
                            }
                            if (!retStr.equals("")) {
                                retStr = retStr.substring(0, retStr.length() - 1);
                                addShop.setText(retStr);
                            } else {
                                addShop.setText("请选择任务类型");
                            }
                        }
                    }
                    freshAddPanel();
                }
            }

        }

        private void freshAddPanel()//餐厅多任务
        {
            fragementid=1;
            if(lst==null)
                return;
            if(shopLst==null)
                return;
            if(lst.size()==0)
                return;
            if(shopLst.size()==0)
                return;
            cacheSch = new ArrayList<SchAddBean>();
            SimpleSpinnerOption shopTemp=new SimpleSpinnerOption();
            for(SimpleSpinnerOption ss:shopLst)
            {
                if(ss.isChecked()){
                    shopTemp=ss;
                    break;
                }
            }
            if(shopTemp!=null && shopTemp.getValue().equals(""))
                return;
            YEARMMDD();
            String str=sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM;
            for (SimpleSpinnerOption s : lst) {
                if(s.isChecked()) {
                    SchAddBean sch = new SchAddBean();
                    sch.setShopid(String.valueOf(shopTemp.getValue()));
                    sch.setShopname(shopTemp.getName());
                    sch.setEmpid(String.valueOf(cn.acewill.yxd.yunxundian.ui.MainActivity.id));
                    sch.setStypeid(String.valueOf(s.getValue()));
                    sch.setSchTypeStr(String.valueOf(s.getName()));
                    sch.setSchStartTime(str);
                    cacheSch.add(sch);
                }
            }
            final SchAddPanelAdapter sapa = new SchAddPanelAdapter(getContext(), cacheSch,new SchAddPanelAdapter.moreTaskCallBack(){
                @Override
                public void Click(SchAddBean bean,View v,int pid) {
                    position=pid;
                    txV=v;
                    //Toast.makeText(getContext(),"test",Toast.LENGTH_SHORT).show();
                    switch (v.getId()){
                        case (R.id.schStartDate):{
                            DatePickerDialog dpd = new DatePickerDialog(getContext(), Datelistener, thisyear, thismonth-1, thisday);
                            dpd.show();//显示DatePickerDialog组件
                            break;
                        }
                        case (R.id.schStartTime):{
                            TimePickerDialog dpd = new TimePickerDialog(getContext(),timeSetListener,9,30,true);
                            dpd.show();//显示DatePickerDialog组件
                            break;
                        }
                    }
                }
                TimePickerDialog.OnTimeSetListener timeSetListener=new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        hour=hourOfDay;
                        minutes=minute;
                        YEARMMDD();
                        cacheSch.get(position).setSchStartTime(sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM);
                        ((TextView)txV).setText(sHH+":"+sMM);
                    }
                };

                DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
                    /**
                     * params：view：该事件关联的组件
                     * params：myyear：当前选择的年
                     * params：monthOfYear：当前选择的月
                     * params：dayOfMonth：当前选择的日
                     */
                    @Override
                    public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {


                        //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
                        thisyear = myyear;
                        thismonth = monthOfYear+1;
                        thisday = dayOfMonth;
                        //更新日期
                        YEARMMDD();
                        updateDate();
                    }

                    //当DatePickerDialog关闭时，更新日期显示
                    private void updateDate() {
                        cacheSch.get(position).setSchStartTime(sYear+"-"+sMonth+"-"+sDay+"T"+sHH+":"+sMM);
                        ((TextView)txV).setText(sYear+"-"+sMonth+"-"+sDay);
                    }
                };

            });
            liSchAdd.setAdapter(sapa);
            sapa.notifyDataSetChanged();
        }

        public void YEARMMDD()
        {
            sYear=String.valueOf(thisyear);
            sMonth=thismonth+"";
            sDay=thisday+"";
            sHH=hour+"";
            sMM=minutes+"";
            if(String.valueOf(thismonth).length()==1)
            {
                sMonth="0"+thismonth;
            }
            if(String.valueOf(thisday).length()==1)
            {
                sDay="0"+thisday;
            }
            if(String.valueOf(hour).length()==1)
            {
                sHH="0"+hour;
            }
            if(String.valueOf(minutes).length()==1)
            {
                sMM="0"+minutes;
            }
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            switch (position){
                case 0:
                    return PlaceholderFragment.newInstance(position + 1);
                case 1:
                    return addFragment2.newInstance(position+1);
                default:
                    return PlaceholderFragment.newInstance(position + 1);
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "任务多餐厅";
                case 1:
                    return "餐厅多任务";
            }
            return null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
            return false;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }
}
